#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <thread>
#include <chrono>
#include "hidbox/hid_device_manager.h"
#include "hidbox/mouse_descriptor_builder.h"
#include "base/logging.h"

using namespace hidbox;

static bool running = true;

void signal_handler(int signal) {
    if (signal == SIGINT || signal == SIGTERM) {
        LOG_INFO("Received signal {}, shutting down...", signal);
        running = false;
    }
}

int main(int argc, char** argv) {
    // 检查 root 权限
    if (geteuid() != 0) {
        std::cerr << "Error: This program must be run as root." << std::endl;
        return 1;
    }

    // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    try {
        LOG_INFO("HID_BOX Passthrough Example");
        LOG_INFO("================================");

        // 创建 HID 设备管理器
        HIDDeviceManager manager;

        // 配置设备
        HIDDeviceConfig config;
        config.auto_detect = true;  // 自动检测模式
        config.input_identifier.vid = 0;  // 0 表示检测第一个 HID 设备
        config.input_identifier.pid = 0;
        config.gadget_name = "hidbox";
        config.hid_number = 0;

        LOG_INFO("Configuring HID device...");
        manager.Configure(config);

        LOG_INFO("Starting passthrough mode...");
        manager.StartPassthrough();

        LOG_INFO("HID passthrough is running. Press Ctrl+C to stop.");

        // 主循环
        while (running) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }

        LOG_INFO("Stopping passthrough...");
        manager.StopPassthrough();

        LOG_INFO("Shutdown complete");
    } catch (const std::exception& e) {
        LOG_ERROR("Fatal error: {}", e.what());
        return 1;
    }

    return 0;
}
